package com.stud.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stud.seckill.common.enums.CacheKeyEnum;
import com.stud.seckill.common.config.CacheService;
import com.stud.seckill.common.auth.UserContext;
import com.stud.seckill.common.exception.Asserts;
import com.stud.seckill.entity.GoodsEntity;
import com.stud.seckill.mapper.SeckillGoodsMapper;
import com.stud.seckill.entity.SeckillGoodsEntity;
import com.stud.seckill.service.SeckillGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 秒杀商品表 服务实现类
 * </p>
 *
 * @author Libra
 * @since 2024-03-30
 */
@Service
public class SeckillGoodsServiceImpl extends ServiceImpl<SeckillGoodsMapper, SeckillGoodsEntity> implements SeckillGoodsService {

    @Autowired
    private CacheService cacheService;

    @Override
    public List<SeckillGoodsEntity> selectList(SeckillGoodsEntity seckillGoods) {
        LambdaQueryWrapper<SeckillGoodsEntity> queryWrapper = Wrappers.lambdaQuery();
        return this.getBaseMapper().selectList(queryWrapper);
    }

    @Override
    public SeckillGoodsEntity get(Long goodsId) {
        SeckillGoodsEntity seckillGoods = (SeckillGoodsEntity) cacheService.get(CacheKeyEnum.秒杀商品, goodsId);
        if (seckillGoods == null) {
            LambdaQueryWrapper<SeckillGoodsEntity> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(SeckillGoodsEntity::getGoodsId, goodsId);
            seckillGoods = this.getBaseMapper().selectOne(queryWrapper);
            cacheService.set(CacheKeyEnum.秒杀商品, goodsId, seckillGoods);
        }
        return seckillGoods;
    }

    @Override
    public void subStore(Long goodsId, Integer stockCount) {
        LambdaUpdateWrapper<SeckillGoodsEntity> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.setSql("stock_count=stock_count-" + stockCount);
        updateWrapper.eq(SeckillGoodsEntity::getGoodsId, goodsId);
        updateWrapper.gt(SeckillGoodsEntity::getStockCount, 0);
        boolean isResult = this.update(updateWrapper);
        if (!isResult) {
            // 扣减数据失败的计数
            cacheService.set(CacheKeyEnum.秒杀监控数据, "orderFail:userId" + UserContext.getUser().getId()+"goodsId"+goodsId, 1);
            Asserts.fail("扣减库存失败");
        }
        // 清除缓存
        cacheService.delete(CacheKeyEnum.秒杀商品, goodsId);
    }

    @Override
    public void initStock() {
        LambdaUpdateWrapper<SeckillGoodsEntity> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(SeckillGoodsEntity::getStockCount, 10);
        updateWrapper.lt(SeckillGoodsEntity::getStockCount, 10);
        this.update(updateWrapper);
    }

}
